<template>
  <div class="account-container">
    <van-form
      @submit="updateUserInfo"
      @failed="onFailed"
      :show-error="false"
      :show-error-message="false"
    >
      <!-- 顶部导航 -->
      <van-nav-bar
        class="bgcolor"
        title="账号中心"
        right-text="保存"
        safe-area-inset-top
        @click-left="$router.go(-1)"
      >
        <template #left>
          <van-icon class="leftIcon" name="arrow-left" size="18" />
        </template>

        <template #right>
          <van-button color="rgb(153, 217, 157)" native-type="submit">
            <span style="color: #1989fa; font-size: 0.37333rem">保存</span>
          </van-button>
        </template>
      </van-nav-bar>

      <!-- 内容 -->
      <div class="main-content">
        <!-- 头像区 -->
        <div class="avatar-wrap">
          <van-image
            round
            class="avatar"
            fit="cover"
            :src="updateUser.avatar"
            @click="show = true"
          />
        </div>

        <div class="baseInfo">
          <van-cell-group class="van-field-bgColor">
            <van-field label="用户名" v-model="updateUser.username" />
            <van-field
              label="密码"
              type="password"
              v-model="updateUser.password"
              :rules="[
                {
                  pattern: passwordPattern,
                  message:
                    '密码必须以字母开头，长度在6~18之间，只能包含字母、数字和下划线',
                },
              ]"
            />
            <van-field
              label="手机号"
              type="tel"
              v-model="updateUser.telephone"
              :rules="[{ pattern: telePattern, message: '手机号码不合法' }]"
            />
            <van-field label="籍贯" v-model="updateUser.address" />
          </van-cell-group>
        </div>

        <van-popup class="popup" v-model="show" close-on-popstate>
          <van-cell-group :border="false">
            <van-cell title="操作" />
          </van-cell-group>
          <van-uploader class="uploadBtn" :after-read="afterRead">
            <van-button color="#fff">
              <span style="color: #323233">更新头像</span>
            </van-button>
          </van-uploader>
        </van-popup>
      </div>
    </van-form>
  </div>
</template>

<script>
import { updateUserInfo } from "@/api/user";
import { mapState } from "vuex";
import { uploadImage } from "@/api/uploadImage";
import { Form } from "vant";
export default {
  name: "Account",

  data() {
    return {
      updateUser: {
        address: "",
        avatar: "",
        id: null,
        password: "",
        telephone: "",
        username: "",
      },

      Avatar: {},

      telePattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      passwordPattern: /^[a-zA-Z]\w{5,17}$/,

      show: false,
    };
  },

  computed: {
    ...mapState("user", ["user"]),
  },

  mounted() {
    console.log("账号中心挂载");
    this.updateUser = { ...this.user };
  },

  activated() {
    console.log("账号中心激活");
    this.updateUser = { ...this.user };
  },

  methods: {
    afterRead(fileParams) {
      console.log("图片上传", fileParams);
      this.Avatar = fileParams.file;

      this.updateUser.avatar = fileParams.content;
      this.show = false;
    },

    /**
     * 更新用户信息并保存---（用户信息更新至数据库后更新vuex与本地存储数据）
     */
    updateUserInfo() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
      });

      let formData = new FormData();
      formData.append("file", this.Avatar);
      uploadImage(formData)
        .then((res) => {
          let imageUrl = res.data;
          this.updateUser.avatar = imageUrl;

          let data = {
            ...this.updateUser,
            avatar: "/upload" + imageUrl.split("/upload")[1],
          };

          return updateUserInfo(data);
        })
        .then((res) => {
          this.$toast.success({
            message: "更新信息成功",
          });
          this.$store.commit("user/setUser", this.updateUser);
          //更新本地存储
          let result = JSON.parse(window.localStorage.getItem("result"));
          result.user = this.updateUser;
          window.localStorage.setItem("result", JSON.stringify(result));
          setTimeout(() => {
            this.$router.go(-1);
          }, 2500);
        });
    },

    /**
     * 表单校验失败的处理
     */
    onFailed(err) {
      if (err.errors[0]) {
        let errMsg = err.errors[0].message;
        this.$dialog.alert({
          title: "提示",
          message: errMsg,
        });
      }
    },
  },
};
</script>

<style scoped>
.popup {
  width: 220px;
}

.uploadBtn,
.uploadBtn > * {
  width: 100%;
}

.bgcolor {
  background-color: rgb(153, 217, 157);
  color: #000;
}

.leftIcon {
  color: #000 !important;
}

.main-content {
  width: 325px;
  height: auto;
  margin: 35px auto;
}

.avatar-wrap {
  width: 120px;
  height: 120px;
  margin: 0 auto;
  padding-bottom: 40px;
}

.avatar {
  width: 120px;
  height: 120px;
}

.van-field-bgColor,
.van-field-bgColor > * {
  background-color: inherit !important;
}
</style>